"""
requests 最流行的请求库 依赖urllib3
"""
import requests


# url = "http://127.0.0.1:5000/"

def get_status():
    res = requests.get("http://127.0.0.1:5000/")
    if res.status_code == 200:
        print(f"请求成功，状态码是{res.status_code}")
    else:
        print(res.status_code)


# get_status()

def get_response():
    res = requests.get("http://127.0.0.1:5000/response_type")
    if res.status_code == 200:
        print(res.text)
        # print(res.content.decode())
        # print(res.json()["info"])
        print(res.headers["Content-Type"], res.encoding)


# get_response()


def get_params():
    res = requests.get("http://127.0.0.1:5000/params?page=1&size=5", params={
        "type": "views",
        "sort": "id",
        "limit": 50
    })
    print(res.json())


# get_params()


def get_data():
    # 默认请求头application/x-www-form-urlencoded
    res = requests.post("http://127.0.0.1:5000/data", data={
        "name": "admin",
        "password": "123456"
    })
    print(res.request.headers["Content-Type"], res.json())


# get_data()


def get_json():
    # 默认请求头application/json
    res = requests.post("http://127.0.0.1:5000/json", json={
        "name": "admin",
        "password": "123456"
    })
    print(res.request.headers["Content-Type"], res.json())


# get_json()


def set_headers():
    headers = {
        "User-Agent": "ozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
        "Referer": "http://127.0.0.1:5000/"
    }

    res = requests.get("http://127.0.0.1:5000/headers", headers=headers)
    if res.status_code == 200:
        print(res.json())
    else:
        print(res.status_code)


# set_headers()

def login():
    res = requests.post("http://127.0.0.1:5000/login", json={
        "username": "admin",
        "password": "123456"
    })
    # print(res.json(), res.cookies)
    # for c in res.cookies:
    #     print(c.name, c.value)
    return res.cookies


# login()


def get_center():
    headers = {
        # "Cookie": "username=zzy;"
    }
    # cookies = {
    #     "username": "ly",
    #     "age": "20"
    # }
    cookies = login()
    res = requests.get("http://127.0.0.1:5000/center", headers=headers, cookies=cookies)
    if res.status_code == 200:
        print(res.json())
    else:
        print(res)


# get_center()

def login_get_usr_info():
    # res = requests.post("http://127.0.0.1:5000/login", json={
    #     "username": "admin",
    #     "password": "123456"
    # })
    # cookies = res.cookies
    # res = requests.get("http://127.0.0.1:5000/center", cookies=cookies)
    # print(res.json())

    # 构建会话实例 实现状态保持
    session = requests.Session()
    session.post("http://127.0.0.1:5000/login", json={
        "username": "admin",
        "password": "123456"
    })
    res = session.get("http://127.0.0.1:5000/center")
    print(res.json())


login_get_usr_info()
